package com.iot.web.controller.device;

import com.alibaba.fastjson.JSONObject;
import com.iot.common.annotation.Log;
import com.iot.common.core.controller.BaseController;
import com.iot.common.core.domain.AjaxResult;
import com.iot.common.core.domain.entity.SysUser;
import com.iot.common.enums.BusinessType;
import com.iot.common.utils.DateUtils;
import com.iot.common.utils.SecurityUtils;
import com.iot.common.utils.TimeHelper;
import com.iot.common.utils.poi.ExcelUtil;
import com.iot.device.domain.*;
import com.iot.device.dto.GasClientDataStatistics;
import com.iot.device.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 *
 * @author iot
 * @date 2023-04-14
 */
@RestController
@RequestMapping("/visual/statistics")
public class StatisticsController extends BaseController
{

    @Autowired
    public IQuakeClientService quakeClientService;
    @Autowired
    public IQuakeEventService quakeEventService;
    @Autowired
    public IGasClientService gasClientService;
    @Autowired
    public IGasEventService gasEventService;
    @Autowired
    public IBeidouClientService beidouClientService;
    @Autowired
    public IBeidouEventService beidouEventService;
    @Autowired
    public IStatisticsService statisticsService;

    /**
     * 查询设备统计
     */
    @GetMapping("/gasDeviceStat")
    public AjaxResult gasDeviceStat()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Map<String, Long> clientStatistics = gasClientService.selectGasClientStatistics(sysUser.isAdmin() ? null : sysUser.getUserId());
        JSONObject obj = new JSONObject();
        obj.put("totalCount", clientStatistics.getOrDefault("totalCount", 0L));
        obj.put("totalOnlineCount", clientStatistics.getOrDefault("onlineCount", 0L));
        return AjaxResult.success(obj);
    }

    /**
     * 首页查询燃气管道报警数据
     */
    @GetMapping("/statisticsTotalGasEvent")
    public AjaxResult statisticsTotalGasEvent()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        if(sysUser.isAdmin()){
            return AjaxResult.success(statisticsService.statisticsTotalGasEvent(null, DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now)));
        }
        else
        {
            return AjaxResult.success(statisticsService.statisticsTotalGasEvent(sysUser.getUserId(), DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now)));
        }
    }

    /**
     * 燃气报警数据分类统计（全部）
     */
    @GetMapping("/gasEventStat")
    public AjaxResult gasEventStat()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        if(sysUser.isAdmin()){
            return AjaxResult.success(statisticsService.statisticsTotalGasEventGroupByType(null));
        }
        else
        {
            return AjaxResult.success(statisticsService.statisticsTotalGasEventGroupByType(sysUser.getUserId()));
        }
    }

    /**
     * 燃气报警数据分类统计（本日）
     */
    @GetMapping("/todayGasEventStat")
    public AjaxResult todayGasEventStat()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        if(sysUser.isAdmin()){
            return AjaxResult.success(statisticsService.statisticsTodayGasEventGroupByType(null, DateUtils.getTimesmorning(now)));
        }
        else
        {
            return AjaxResult.success(statisticsService.statisticsTodayGasEventGroupByType(sysUser.getUserId(), DateUtils.getTimesmorning(now)));
        }
    }

    /**
     * 燃气报警数据分类统计（本月）
     */
    @GetMapping("/monthGasEventStat")
    public AjaxResult monthGasEventStat()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        if(sysUser.isAdmin()){
            return AjaxResult.success(statisticsService.statisticsMonthGasEventGroupByType(null, DateUtils.getTimesMonthStartMorning(now)));
        }
        else
        {
            return AjaxResult.success(statisticsService.statisticsMonthGasEventGroupByType(sysUser.getUserId(), DateUtils.getTimesMonthStartMorning(now)));
        }
    }

    /**
     * 燃气报警近30日数据趋势
     */
    @GetMapping("/thirtyDaysGasEventTrend")
    public AjaxResult thirtyDaysGasEventTrend()
    {
        Date now = DateUtils.getNowDate();
        // 近三十天事件
        Date startTime = DateUtils.getTimesmorning(DateUtils.addDays(now, -31));
        Date endTime = DateUtils.getTimesnight(DateUtils.addDays(now, -1));
        SysUser sysUser = SecurityUtils.getSysUser();
        List<Map<String, Object>> thirtyDaysChangeList = statisticsService.selectGasEventTrendStatisticsByDuration(startTime, endTime, sysUser.isAdmin() ? null : sysUser.getUserId());
        TreeMap<String, Map<String, Long>> thirtyDaysChange = new TreeMap(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return DateUtils.parseDate(o1).compareTo(DateUtils.parseDate(o2));
            }
        });
        List<String> days = DateUtils.getDayListOfDate(startTime, endTime);
        for(String day : days){
            thirtyDaysChange.put(day, null);
        }
        for(Map<String, Object> map : thirtyDaysChangeList){
            String date = map.get("eventDate").toString();
            Long position = Long.parseLong(map.get("position").toString());
            Long Ii = Long.parseLong(map.get("Ii").toString());
            Long angle = Long.parseLong(map.get("angle").toString());
            Map<String, Long> m = new HashMap();
            m.put("position", position);
            m.put("Ii", Ii);
            m.put("angle", angle);
            m.put("total", position + angle + Ii);
            thirtyDaysChange.put(date, m);
        }
        JSONObject data = new JSONObject();
        data.put("days", days);
        List<Long> IiList = new ArrayList<>();
        List<Long> positionList = new ArrayList<>();
        List<Long> angleList = new ArrayList<>();
        List<Long> totalList = new ArrayList<>();
        for(String day : days){
            Map<String, Long> dayData = thirtyDaysChange.get(day);
            IiList.add(dayData == null ? 0L : dayData.get("Ii"));
            positionList.add(dayData == null ? 0L : dayData.get("position"));
            angleList.add(dayData == null ? 0L : dayData.get("angle"));
            totalList.add(dayData == null ? 0L : dayData.get("total"));
        }
        // data.put("thirtyDaysChange", thirtyDaysChange);
        data.put("IiList", IiList);
        data.put("positionList", positionList);
        data.put("angleList", angleList);
        data.put("totalList", totalList);
        return AjaxResult.success(data);
    }

    /**
     * 燃气报警可视化概览页数据
     */
    @GetMapping("/gasEventThisYearStatistics")
    public AjaxResult gasEventThisYearStatistics()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        Map<String, Object> gasEventThisYearStatistics = statisticsService.selectGasEventThisYearStatistics(sysUser.isAdmin() ? null : sysUser.getUserId(),
                DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now));
        String thisMonth = DateUtils.parseDateToStr(now, "yyyy年MM月");
        String lastMonth = DateUtils.parseDateToStr(DateUtils.addMonths(now, -1), "yyyy年MM月");
        gasEventThisYearStatistics.put("thisMonth", thisMonth);
        gasEventThisYearStatistics.put("lastMonth", lastMonth);
        return AjaxResult.success(gasEventThisYearStatistics);
    }

    /**
     * 燃气报警可视化概览页数据
     */
    @GetMapping("/gasVisualStatistics")
    public AjaxResult gasVisualStatistics()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        Map<String, Long> countGasClient = gasClientService.countGasClientsByUserId(sysUser.isAdmin() ? null : sysUser.getUserId());
        List<Map<String, Long>> eventRank = gasEventService.selectGasEventRankByClient(sysUser.isAdmin() ? null : sysUser.getUserId(), 6L);
        Map<String, Object> gasEventThisYearStatistics = statisticsService.selectGasEventThisYearStatistics(sysUser.isAdmin() ? null : sysUser.getUserId(),
                DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now));
        JSONObject data = new JSONObject();
        data.put("countGasClient", countGasClient);
        data.put("eventRank", eventRank);
        data.put("gasEventThisYearStatistics", gasEventThisYearStatistics);
        return AjaxResult.success(data);
    }

    /**
     * 燃气报警可视化概览页数据
     */
    @GetMapping("/gasDataVisual")
    public AjaxResult gasDataVisual()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        GasClient queryGasClient = new GasClient();
        if(!sysUser.isAdmin()){
            queryGasClient.setUserId(sysUser.getUserId());
        }
        List<GasClient> gasClientList = gasClientService.selectGasClientWithInfos(queryGasClient);
        List<GasEvent> gasEventList = gasEventService.selectRecentGasEventList(sysUser.isAdmin() ? null : sysUser.getUserId(), 6L);
        Map<String, Object> gasEventThisYearStatistics = statisticsService.selectGasEventThisYearStatistics(sysUser.isAdmin() ? null : sysUser.getUserId(),
                DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now));
        String thisMonth = DateUtils.parseDateToStr(now, "yyyy年MM月");
        String lastMonth = DateUtils.parseDateToStr(DateUtils.addMonths(now, -1), "yyyy年MM月");
        gasEventThisYearStatistics.put("thisMonth", thisMonth);
        gasEventThisYearStatistics.put("lastMonth", lastMonth);
        JSONObject data = new JSONObject();
        data.put("gasClientList", gasClientList);
        data.put("gasEventList", gasEventList);
        data.put("gasEventThisYearStatistics", gasEventThisYearStatistics);
        return AjaxResult.success(data);
    }

    /**
     * 燃气管道检测统计数据
     */
    @GetMapping("/gasClientDataStatistics")
    public AjaxResult gasClientDataStatistics(@RequestParam(name = "hourLimit", defaultValue = "24") int hourLimit, @RequestParam(name="deptId", required = false) Long deptId)
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        List<GasClientDataStatistics> gasEventThisYearStatistics = statisticsService.selectGasClientDataStatistics(sysUser.isAdmin() ? null : sysUser.getUserId(), hourLimit, deptId);
        return AjaxResult.success(gasEventThisYearStatistics);
    }

    /**
     * 导出燃气监测设备列表
     */
    @PreAuthorize("@ss.hasPermi('device:gasClientDataStatistics:export')")
    @Log(title = "燃气管道监测设备数据", businessType = BusinessType.EXPORT)
    @PostMapping("/gasClientDataStatistics/export")
    public void gasClientDataStatisticsExport(HttpServletResponse response, @RequestParam(name = "hourLimit", defaultValue = "24") int hourLimit, @RequestParam(name="deptId", required = false) Long deptId)
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        List<GasClientDataStatistics> gasEventThisYearStatistics = statisticsService.selectGasClientDataStatistics(sysUser.isAdmin() ? null : sysUser.getUserId(), hourLimit, deptId);
        ExcelUtil<GasClientDataStatistics> util = new ExcelUtil<GasClientDataStatistics>(GasClientDataStatistics.class);
        util.exportExcel(response, gasEventThisYearStatistics, "燃气管道监测设备数据");
    }


    /*TODO********************************************************  环境监测设备 **********************************************************************************************/



    /**
     * 查询设备统计
     */
    @GetMapping("/quakeDeviceStat")
    public AjaxResult quakeDeviceStat()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Map<String, Long> clientStatistics = quakeClientService.selectQuakeClientStatistics(sysUser.isAdmin() ? null : sysUser.getUserId());
        JSONObject obj = new JSONObject();
        obj.put("totalCount", clientStatistics.getOrDefault("totalCount", 0L));
        obj.put("totalOnlineCount", clientStatistics.getOrDefault("onlineCount", 0L));
        return AjaxResult.success(obj);
    }

    /**
     * 首页查询报警数据
     */
    @GetMapping("/statisticsTotalQuakeEvent")
    public AjaxResult statisticsTotalQuakeEvent()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        if(sysUser.isAdmin()){
            return AjaxResult.success(statisticsService.statisticsTotalQuakeEvent(null, DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now)));
        }
        else
        {
            return AjaxResult.success(statisticsService.statisticsTotalQuakeEvent(sysUser.getUserId(), DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now)));
        }
    }
    /**
     * 环境监测报警可视化概览页数据
     */
    @GetMapping("/quakeDataVisual")
    public AjaxResult quakeDataVisual()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        QuakeClient queryQuakeClient = new QuakeClient();
        if(!sysUser.isAdmin()){
            queryQuakeClient.setUserId(sysUser.getUserId());
        }
        Date now = DateUtils.getNowDate();
        List<QuakeClient> quakeClientList = quakeClientService.selectQuakeClientList(queryQuakeClient);
        TimeHelper.start("quakeEventService.selectRecentQuakeEventList");
        List<QuakeEvent> quakeEventList = quakeEventService.selectRecentQuakeEventList(sysUser.isAdmin() ? null : sysUser.getUserId(), 6L);
        System.out.println("quakeEventService.selectRecentQuakeEventList执行耗时：" + TimeHelper.end("quakeEventService.selectRecentQuakeEventList"));
        TimeHelper.start("statisticsService.selectQuakeEventThisYearStatistics");
        Map<String, Object> quakeEventThisYearStatistics = statisticsService.selectQuakeEventThisYearStatistics(sysUser.isAdmin() ? null : sysUser.getUserId(),
                DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now));
        System.out.println("statisticsService.selectQuakeEventThisYearStatistics执行耗时：" + TimeHelper.end("statisticsService.selectQuakeEventThisYearStatistics"));
        String thisMonth = DateUtils.parseDateToStr(now, "yyyy年MM月");
        String lastMonth = DateUtils.parseDateToStr(DateUtils.addMonths(now, -1), "yyyy年MM月");
        quakeEventThisYearStatistics.put("thisMonth", thisMonth);
        quakeEventThisYearStatistics.put("lastMonth", lastMonth);
        JSONObject data = new JSONObject();
        data.put("quakeClientList", quakeClientList);
        data.put("quakeEventList", quakeEventList);
        data.put("quakeEventThisYearStatistics", quakeEventThisYearStatistics);
        return AjaxResult.success(data);
    }

    /**
     * 环境监测报警可视化概览页数据
     */
    @GetMapping("/quakeVisualStatistics")
    public AjaxResult quakeVisualStatistics()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        Map<String, Long> countQuakeClient = quakeClientService.countQuakeClientsByUserId(sysUser.isAdmin() ? null : sysUser.getUserId());
        List<Map<String, Long>> eventRank = quakeEventService.selectQuakeEventRankByClient(sysUser.isAdmin() ? null : sysUser.getUserId(), 6L);
        Map<String, Object> quakeEventThisYearStatistics = statisticsService.selectQuakeEventThisYearStatistics(sysUser.isAdmin() ? null : sysUser.getUserId(),
                DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now));
        JSONObject data = new JSONObject();
        data.put("countQuakeClient", countQuakeClient);
        data.put("eventRank", eventRank);
        data.put("quakeEventThisYearStatistics", quakeEventThisYearStatistics);
        return AjaxResult.success(data);
    }

    /**
     *
     */
    @GetMapping("/quakeEventThisYearStatistics")
    public AjaxResult quakeEventThisYearStatistics()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        Map<String, Object> quakeEventThisYearStatistics = statisticsService.selectQuakeEventThisYearStatistics(sysUser.isAdmin() ? null : sysUser.getUserId(),
                DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now));
        String thisMonth = DateUtils.parseDateToStr(now, "yyyy年MM月");
        String lastMonth = DateUtils.parseDateToStr(DateUtils.addMonths(now, -1), "yyyy年MM月");
        quakeEventThisYearStatistics.put("thisMonth", thisMonth);
        quakeEventThisYearStatistics.put("lastMonth", lastMonth);
        return AjaxResult.success(quakeEventThisYearStatistics);
    }



    /**
     * 环境监测报警近30日数据趋势
     */
    @GetMapping("/thirtyDaysQuakeEventTrend")
    public AjaxResult thirtyDaysQuakeEventTrend()
    {
        Date now = DateUtils.getNowDate();
        // 近三十天事件
        Date startTime = DateUtils.getTimesmorning(DateUtils.addDays(now, -31));
        Date endTime = DateUtils.getTimesnight(DateUtils.addDays(now, -1));
        SysUser sysUser = SecurityUtils.getSysUser();
        TimeHelper.start("statisticsService.selectQuakeEventTrendStatisticsByDuration");
        List<Map<String, Object>> thirtyDaysChangeList = statisticsService.selectQuakeEventTrendStatisticsByDuration(startTime, endTime, sysUser.isAdmin() ? null : sysUser.getUserId());
        System.out.println("statisticsService.selectQuakeEventTrendStatisticsByDuration执行耗时：" + TimeHelper.end("statisticsService.selectQuakeEventTrendStatisticsByDuration"));
        TreeMap<String, Map<String, Long>> thirtyDaysChange = new TreeMap(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return DateUtils.parseDate(o1).compareTo(DateUtils.parseDate(o2));
            }
        });
        List<String> days = DateUtils.getDayListOfDate(startTime, endTime);
        for(String day : days){
            thirtyDaysChange.put(day, null);
        }
        for(Map<String, Object> map : thirtyDaysChangeList){
            String date = map.get("eventDate").toString();
            Long position = Long.parseLong(map.get("position").toString());
            Long Ii = Long.parseLong(map.get("Ii").toString());
            Long angle = Long.parseLong(map.get("angle").toString());
            Map<String, Long> m = new HashMap();
            m.put("position", position);
            m.put("Ii", Ii);
            m.put("angle", angle);
            m.put("total", position + angle + Ii);
            thirtyDaysChange.put(date, m);
        }
        JSONObject data = new JSONObject();
        data.put("days", days);
        List<Long> IiList = new ArrayList<>();
        List<Long> positionList = new ArrayList<>();
        List<Long> angleList = new ArrayList<>();
        List<Long> totalList = new ArrayList<>();
        for(String day : days){
            Map<String, Long> dayData = thirtyDaysChange.get(day);
            IiList.add(dayData == null ? 0L : dayData.get("Ii"));
            positionList.add(dayData == null ? 0L : dayData.get("position"));
            angleList.add(dayData == null ? 0L : dayData.get("angle"));
            totalList.add(dayData == null ? 0L : dayData.get("total"));
        }
        // data.put("thirtyDaysChange", thirtyDaysChange);
        data.put("IiList", IiList);
        data.put("positionList", positionList);
        data.put("angleList", angleList);
        data.put("totalList", totalList);
        return AjaxResult.success(data);
    }


    /**
     * 报警数据分类统计（全部）
     */
    @GetMapping("/quakeEventStat")
    public AjaxResult quakeEventStat()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        if(sysUser.isAdmin()){
            return AjaxResult.success(statisticsService.statisticsTotalQuakeEventGroupByType(null));
        }
        else
        {
            return AjaxResult.success(statisticsService.statisticsTotalQuakeEventGroupByType(sysUser.getUserId()));
        }
    }

    /**
     * 报警数据分类统计（本日）
     */
    @GetMapping("/todayQuakeEventStat")
    public AjaxResult todayQuakeEventStat()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        if(sysUser.isAdmin()){
            return AjaxResult.success(statisticsService.statisticsTodayQuakeEventGroupByType(null, DateUtils.getTimesmorning(now)));
        }
        else
        {
            return AjaxResult.success(statisticsService.statisticsTodayQuakeEventGroupByType(sysUser.getUserId(), DateUtils.getTimesmorning(now)));
        }
    }

    /**
     * 报警数据分类统计（本月）
     */
    @GetMapping("/monthQuakeEventStat")
    public AjaxResult monthQuakeEventStat()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        if(sysUser.isAdmin()){
            return AjaxResult.success(statisticsService.statisticsMonthQuakeEventGroupByType(null, DateUtils.getTimesMonthStartMorning(now)));
        }
        else
        {
            return AjaxResult.success(statisticsService.statisticsMonthQuakeEventGroupByType(sysUser.getUserId(), DateUtils.getTimesMonthStartMorning(now)));
        }
    }




    /*TODO********************************************************  北斗环境监测设备 **********************************************************************************************/



    /**
     * 查询设备统计
     */
    @GetMapping("/beidouDeviceStat")
    public AjaxResult beidouBeidouDeviceStat()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Map<String, Long> clientStatistics = beidouClientService.selectBeidouClientStatistics(sysUser.isAdmin() ? null : sysUser.getUserId());
        JSONObject obj = new JSONObject();
        obj.put("totalCount", clientStatistics.getOrDefault("totalCount", 0L));
        obj.put("totalOnlineCount", clientStatistics.getOrDefault("onlineCount", 0L));
        return AjaxResult.success(obj);
    }

    /**
     * 首页查询报警数据
     */
    @GetMapping("/statisticsTotalBeidouEvent")
    public AjaxResult statisticsTotalBeidouEvent()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        if(sysUser.isAdmin()){
            return AjaxResult.success(statisticsService.statisticsTotalBeidouEvent(null, DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now)));
        }
        else
        {
            return AjaxResult.success(statisticsService.statisticsTotalBeidouEvent(sysUser.getUserId(), DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now)));
        }
    }
    /**
     * 环境监测报警可视化概览页数据
     */
    @GetMapping("/beidouDataVisual")
    public AjaxResult beidouDataVisual()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        BeidouClient queryBeidouClient = new BeidouClient();
        if(!sysUser.isAdmin()){
            queryBeidouClient.setUserId(sysUser.getUserId());
        }
        Date now = DateUtils.getNowDate();
        List<BeidouClient> beidouClientList = beidouClientService.selectBeidouClientList(queryBeidouClient);
        TimeHelper.start("beidouEventService.selectRecentBeidouEventList");
        List<BeidouEvent> beidouEventList = beidouEventService.selectRecentBeidouEventList(sysUser.isAdmin() ? null : sysUser.getUserId(), 6L);
        System.out.println("beidouEventService.selectRecentBeidouEventList执行耗时：" + TimeHelper.end("beidouEventService.selectRecentBeidouEventList"));
        TimeHelper.start("statisticsService.selectBeidouEventThisYearStatistics");
        Map<String, Object> beidouEventThisYearStatistics = statisticsService.selectBeidouEventThisYearStatistics(sysUser.isAdmin() ? null : sysUser.getUserId(),
                DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now));
        System.out.println("statisticsService.selectBeidouEventThisYearStatistics执行耗时：" + TimeHelper.end("statisticsService.selectBeidouEventThisYearStatistics"));
        String thisMonth = DateUtils.parseDateToStr(now, "yyyy年MM月");
        String lastMonth = DateUtils.parseDateToStr(DateUtils.addMonths(now, -1), "yyyy年MM月");
        beidouEventThisYearStatistics.put("thisMonth", thisMonth);
        beidouEventThisYearStatistics.put("lastMonth", lastMonth);
        JSONObject data = new JSONObject();
        data.put("beidouClientList", beidouClientList);
        data.put("beidouEventList", beidouEventList);
        data.put("beidouEventThisYearStatistics", beidouEventThisYearStatistics);
        return AjaxResult.success(data);
    }

    /**
     * 环境监测报警可视化概览页数据
     */
    @GetMapping("/beidouVisualStatistics")
    public AjaxResult beidouVisualStatistics()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        Map<String, Long> countBeidouClient = beidouClientService.countBeidouClientsByUserId(sysUser.isAdmin() ? null : sysUser.getUserId());
        List<Map<String, Long>> eventRank = beidouEventService.selectBeidouEventRankByClient(sysUser.isAdmin() ? null : sysUser.getUserId(), 6L);
        Map<String, Object> beidouEventThisYearStatistics = statisticsService.selectBeidouEventThisYearStatistics(sysUser.isAdmin() ? null : sysUser.getUserId(),
                DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now));
        JSONObject data = new JSONObject();
        data.put("countBeidouClient", countBeidouClient);
        data.put("eventRank", eventRank);
        data.put("beidouEventThisYearStatistics", beidouEventThisYearStatistics);
        return AjaxResult.success(data);
    }

    /**
     *
     */
    @GetMapping("/beidouEventThisYearStatistics")
    public AjaxResult beidouEventThisYearStatistics()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        Map<String, Object> beidouEventThisYearStatistics = statisticsService.selectBeidouEventThisYearStatistics(sysUser.isAdmin() ? null : sysUser.getUserId(),
                DateUtils.getTimesmorning(now), DateUtils.getTimesMonthStartMorning(now));
        String thisMonth = DateUtils.parseDateToStr(now, "yyyy年MM月");
        String lastMonth = DateUtils.parseDateToStr(DateUtils.addMonths(now, -1), "yyyy年MM月");
        beidouEventThisYearStatistics.put("thisMonth", thisMonth);
        beidouEventThisYearStatistics.put("lastMonth", lastMonth);
        return AjaxResult.success(beidouEventThisYearStatistics);
    }



    /**
     * 环境监测报警近30日数据趋势
     */
    @GetMapping("/thirtyDaysBeidouEventTrend")
    public AjaxResult thirtyDaysBeidouEventTrend()
    {
        Date now = DateUtils.getNowDate();
        // 近三十天事件
        Date startTime = DateUtils.getTimesmorning(DateUtils.addDays(now, -31));
        Date endTime = DateUtils.getTimesnight(DateUtils.addDays(now, -1));
        SysUser sysUser = SecurityUtils.getSysUser();
        TimeHelper.start("statisticsService.selectBeidouEventTrendStatisticsByDuration");
        List<Map<String, Object>> thirtyDaysChangeList = statisticsService.selectBeidouEventTrendStatisticsByDuration(startTime, endTime, sysUser.isAdmin() ? null : sysUser.getUserId());
        System.out.println("statisticsService.selectBeidouEventTrendStatisticsByDuration执行耗时：" + TimeHelper.end("statisticsService.selectBeidouEventTrendStatisticsByDuration"));
        TreeMap<String, Map<String, Long>> thirtyDaysChange = new TreeMap(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return DateUtils.parseDate(o1).compareTo(DateUtils.parseDate(o2));
            }
        });
        List<String> days = DateUtils.getDayListOfDate(startTime, endTime);
        for(String day : days){
            thirtyDaysChange.put(day, null);
        }
        for(Map<String, Object> map : thirtyDaysChangeList){
            if(map.get("eventDate") == null){
                continue;
            }
            String date = map.get("eventDate").toString();
            Long position = Long.parseLong(map.get("position").toString());
            Long Ii = Long.parseLong(map.get("Ii").toString());
            Long angle = Long.parseLong(map.get("angle").toString());
            Map<String, Long> m = new HashMap();
            m.put("position", position);
            m.put("Ii", Ii);
            m.put("angle", angle);
            m.put("total", position + angle + Ii);
            thirtyDaysChange.put(date, m);
        }
        JSONObject data = new JSONObject();
        data.put("days", days);
        List<Long> IiList = new ArrayList<>();
        List<Long> positionList = new ArrayList<>();
        List<Long> angleList = new ArrayList<>();
        List<Long> totalList = new ArrayList<>();
        for(String day : days){
            Map<String, Long> dayData = thirtyDaysChange.get(day);
            IiList.add(dayData == null ? 0L : dayData.get("Ii"));
            positionList.add(dayData == null ? 0L : dayData.get("position"));
            angleList.add(dayData == null ? 0L : dayData.get("angle"));
            totalList.add(dayData == null ? 0L : dayData.get("total"));
        }
        // data.put("thirtyDaysChange", thirtyDaysChange);
        data.put("IiList", IiList);
        data.put("positionList", positionList);
        data.put("angleList", angleList);
        data.put("totalList", totalList);
        return AjaxResult.success(data);
    }


    /**
     * 报警数据分类统计（全部）
     */
    @GetMapping("/beidouEventStat")
    public AjaxResult beidouEventStat()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        if(sysUser.isAdmin()){
            return AjaxResult.success(statisticsService.statisticsTotalBeidouEventGroupByType(null));
        }
        else
        {
            return AjaxResult.success(statisticsService.statisticsTotalBeidouEventGroupByType(sysUser.getUserId()));
        }
    }

    /**
     * 报警数据分类统计（本日）
     */
    @GetMapping("/todayBeidouEventStat")
    public AjaxResult todayBeidouEventStat()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        if(sysUser.isAdmin()){
            return AjaxResult.success(statisticsService.statisticsTodayBeidouEventGroupByType(null, DateUtils.getTimesmorning(now)));
        }
        else
        {
            return AjaxResult.success(statisticsService.statisticsTodayBeidouEventGroupByType(sysUser.getUserId(), DateUtils.getTimesmorning(now)));
        }
    }

    /**
     * 报警数据分类统计（本月）
     */
    @GetMapping("/monthBeidouEventStat")
    public AjaxResult monthBeidouEventStat()
    {
        SysUser sysUser = SecurityUtils.getSysUser();
        Date now = DateUtils.getNowDate();
        if(sysUser.isAdmin()){
            return AjaxResult.success(statisticsService.statisticsMonthBeidouEventGroupByType(null, DateUtils.getTimesMonthStartMorning(now)));
        }
        else
        {
            return AjaxResult.success(statisticsService.statisticsMonthBeidouEventGroupByType(sysUser.getUserId(), DateUtils.getTimesMonthStartMorning(now)));
        }
    }
}
